package io.jee.caisan.weixin.config.web.interceptor;

import java.util.Enumeration;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import io.jee.caisan.weixin.config.ConfigProperties;
import io.jee.caisan.weixin.config.SessionManager;
import io.jee.caisan.weixin.service.MemberService;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;

public class WxmpOpenidInterceptor extends HandlerInterceptorAdapter {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource
	private MemberService memberService;
	
	@Resource
	private SessionManager sessionManager;
	
	@Resource
	private ConfigProperties configProperties;
	
	@Resource
	private WxMpService wxService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Enumeration<?> names = request.getHeaderNames();
		this.logger.info("===== Headers ==============================================================");
		this.logger.info("url : " + request.getRequestURL());
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			this.logger.info(name + " : " + request.getHeader(name));
		}
		this.logger.info("now service sessionid : " + request.getSession().getId());
		this.logger.info("===== Parameters ==============================================================");
		Enumeration<?> enu = request.getParameterNames();
		while (enu.hasMoreElements()) {
			String paraName = (String) enu.nextElement();
			this.logger.info(paraName + " : " + request.getParameter(paraName));
		}
		this.logger.info("===== Others ==============================================================");
		// 转换为外网的URL
		String url = request.getRequestURL().toString();
		
		if(url.startsWith("http://127.0.0.1")) {
			if(!StringUtils.hasText(sessionManager.getSessionOpenid(request))) {
				sessionManager.setSessionOpenid(request, "oU2ACs3XZ62GPSZXJJ26R3A3I77M");
			}
			return true;
		}
		
		String serverUrl = configProperties.getServer().getUrl();
		if(!url.startsWith(serverUrl)) {
			url = serverUrl + url;
		}
		
		// 若openid不存在，则获取openid并且加入到session
		if(!StringUtils.hasText(sessionManager.getSessionOpenid(request))) {
			String code = request.getParameter("code");
			if(!StringUtils.hasText(code)){
				String oauth2Url = wxService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_BASE, "LOGIN");
				this.logger.info("not openid is redirect : " + oauth2Url);
				response.sendRedirect(oauth2Url);
				return false;
			} else {
				WxMpOAuth2AccessToken oauth2AccessToken = wxService.oauth2getAccessToken(code);
				sessionManager.setSessionOpenid(request, oauth2AccessToken.getOpenId());
			}
		}
		
		
		this.logger.info("SessionOpenid ： " + sessionManager.getSessionOpenid(request));
		this.logger.info("===== END ==============================================================");
		return true;
	}
}